package imdb_db;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import types.*;

import javax.net.ssl.HttpsURLConnection;
/**
 * this class gives imdb api response of queries and return a list of movies generated form the response.
 * @author chenji
 *
 */
public class Imdb {

	public static void main(String[] args) throws Exception {
		sendGet("Justin%20Bieber:%20Believe");
	}

	// HTTP GET request
	public static List<Movie> sendGet(String qry) throws Exception {
		String url = "http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q=" + qry;
		//System.out.println(url);
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("User-Agent", "Mozilla/5.0");

		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
		String inputLine;
		StringBuffer response = new StringBuffer();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		
		List<Movie> movieList = new ArrayList<Movie>();
		String res = response.toString();
		res = res.substring(1, res.length() - 1);

		for (String tt : res.split("}]")) {
			//System.out.println(tt);
			if (tt.contains("title_popular") || tt.contains("title_exact") || tt.contains("title_substring") || tt.contains("title_approx")) {
				tt = tt.substring(tt.indexOf("[{") + 2);
				for (String r : tt.split("\\},\\{")) {
					String[] keys = { "\"id\"", "\"title\"", "\"title_description\"" };
					Map<String, String> values = new HashMap<String, String>();
					//System.out.println(r);
					for (String key : keys) {
						int start = r.indexOf(key) + key.length() + 2;
						//System.out.println(start + ":" + r.indexOf('\"', start));
						values.put(key, r.substring(start, r.indexOf('\"', start)));
						//System.out.println(key + ":" + values.get(key));
					}
					if (values.get("\"title_description\"").matches("[0-9]{4}(/[IVX]+)?,.*a href=.*")) {
						movieList.add(new Movie(values.get(keys[0]), values.get(keys[1]), values.get(keys[2]), "movie"));
					}	
					else if (values.get("\"title_description\"").matches("[0-9]{4}(/[IVX]+)? documentary,.*a href=.*")) { 
						movieList.add(new Movie(values.get(keys[0]), values.get(keys[1]), values.get(keys[2]), "documentary"));
					}
				}
			}
		}
		return movieList;
	}
}